package com.gxa.controller.statisticalControl;

import com.gxa.pojo.entity.tjgl.ChargeOverview;
import com.gxa.pojo.entity.tjgl.ChargeSummary;
import com.gxa.pojo.entity.tjgl.util.DateInfo;
import com.gxa.service.statistical.ChargeService;
import com.gxa.utils.CustomResult;
import com.gxa.utils.ResultUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author IKE <hp1041735092@outlook.jp>
 * @date 26/2/2024
 */

@RestController
@RequestMapping("/statistic/charge")
public class ChargeController {
    @Resource
    private ChargeService chargeService;

    @GetMapping("/getSummary")
    /*
     * option1:bedArea
     * option2:operator
     * option3:payWay
     */
    public CustomResult<List<ChargeSummary>> queryChargeData(
            @RequestParam(defaultValue = "bedArea") String option,
            @RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") String date       //not null
    ){

        DateInfo parsedDate = DateInfo.fromString(date);

        List<ChargeSummary> summaryList = chargeService.queryChargeData(option,parsedDate);

        return ResultUtils.buildSuccessResponse(summaryList);
    }

    @GetMapping("getChargeOverview")
    public CustomResult<ChargeOverview> queryChargeOverview(
            @RequestParam(defaultValue = "",required = false) String beginDate,
            @RequestParam(defaultValue = "",required = false) String endDate
    ){
        /*nearly a month*/
        LocalDate endDateDefault = LocalDate.now();
        LocalDate beginDateDefault = endDateDefault.minusMonths(1);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate parsedEndDate = parseStr2Date(endDateDefault,endDate,dtf);
        LocalDate parsedBeginDate = parseStr2Date(beginDateDefault,beginDate,dtf);

        /*determine date order*/
        LocalDate checkedBeginDate = parsedBeginDate;
        LocalDate checkedEndDate = parsedEndDate;
        if (parsedEndDate.isBefore(parsedBeginDate)){
            checkedBeginDate = parsedEndDate;
            checkedEndDate = endDateDefault;    //set endDate to today
        }

        System.out.println("beginDate:"+checkedBeginDate+" endDate:"+checkedEndDate);
        ChargeOverview co = chargeService.queryChargeOverview(checkedBeginDate,checkedEndDate);
        return ResultUtils.buildSuccessResponse(co);
    }

    private LocalDate parseStr2Date(LocalDate dateDefault, String dateStr, DateTimeFormatter dtf) {
        try {
            return LocalDate.parse(dateStr,dtf);
        }catch (Exception e){
            return dateDefault;
        }
    }


}
